package com.ironman.mes.convention;

import com.ironman.mes.convention.exception.MesException;
import com.ironman.mes.entity.Res;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;

@Slf4j
@Component
public class GlobalResultInterceptor implements RouterInterceptor {

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        chain.doIntercept(ctx, mainHandler);
    }

    /**
     * 提交结果（ render 执行前调用）
     */
    @Override
    public Object postResult(Context ctx, Object result) throws Throwable {
        if (ctx.path().startsWith("/solon-admin")) {
            return result;
        }
        if (result instanceof MesException) {
            //自定义异常处理
            return Res.failure(((MesException) result).getErrorCode(), ((MesException) result).getMessage());
        } else {
            if (result instanceof Res) {
                return result;
            }
            return Res.ok(result);
        }
    }
}